<template>
  <draggable v-model="spotsList" @start="dragStart" @end="dragEnd" item-key="id">
    <template #item="{ element, index }">
      <div class="spot-container">
        <div class="spot-card">

          <el-button class="delete-button" type="danger" :icon="Minus" circle size="small"
            @click.stop="handleDelete(index)" />
          <div class="spot-name">{{ element.name }}</div>
          <!-- <div class="spot-desc">{{ element.description }}</div> -->
          <div class="spot-time">
            建议游览时间：{{ element.recommendedVisitTime || '暂无时间信息' }}
          </div>
          <div class="robot-icon" @mouseenter="showTooltip(index)" @mouseleave="hideTooltip"
            @click="handleRobotClick(element)">
            <el-icon>

              <Service />

            </el-icon>

            <div class="robot-tooltip" v-if="activeTooltipIndex === index">
              <template v-if="getSpotAnalysis(element)">
                <div class="tooltip-section">
                  <h4>游览建议</h4>
                  <p class="truncated-text">{{ getSpotAnalysis(element).visiting_tips }}</p>
                </div>
                <div class="tooltip-hint">
                  {{ getSpotAnalysis(element) === DEFAULT_TIPS ? '暂无分析信息' : '点击下方按钮进一步了解' }}
                </div>
                <!-- 添加调试信息
                <div class="debug-info">
                  <p>Spot ID: {{ element.attractionId }}</p>
                  <p>Analysis Results: {{ props.spotAnalysisResults.length }}</p>
                </div> -->

              </template>

            </div>

          </div>
        </div>
        <div v-if="!isDragging && index < spotsList.length - 1" class="transport-button"
          @wheel.prevent="handleWheel($event, index)" @click="toggleRoute(index)">
          <transition-group name="slide" tag="div" class="transport-text-container">
            <span :key="getConnectionInfo(index)?.mode || '计算中'" class="transport-text"
              :class="{ 'active': getConnectionInfo(index)?.visible }">
              {{ getTransportText(index) }}
            </span>
          </transition-group>
        </div>
      </div>
    </template>
  </draggable>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch } from 'vue'
import draggable from 'vuedraggable'
import { Service, Minus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
import { createTravelPlan } from '@/api/TravelPlan'
import { createPlanAttraction } from '@/api/PlanAttraction'
import { createTransportationPlan } from '@/api/TransportationPlan'
import { useUserStore } from '@/stores/UserStore';
import { getPlanAttractionListByPlanId } from '@/api/PlanAttraction'
import { getAttractionInfo } from '@/api/Attraction'
import { getTransportationPlansByPlanId } from '@/api/TransportationPlan'
import { deleteTravelPlan } from '@/api/TravelPlan'

interface Spot {
  attractionId: number
  name: string
  description: string
  duration?: number
  aiSuggestion?: string
  // ... 其他属性
}

interface SpotAnalysisDetail {
  spotId: number
  name: string
  analysis: {
    detailed_analysis: string
    visiting_tips: string
    budget_estimation: string
    recommended_duration: string
  }
}

interface Transport {
  startId: number;
  endId: number;
  mode: '步行' | '骑行' | '驾车';
  duration?: number;
  distance?: number;
  visible: boolean;
}

const props = defineProps<{
  spots: Spot[]
  spotAnalysisResults: SpotAnalysisDetail[]
  mapRef: {  // 添加 mapRef prop
    type: Object,
    required: true
  }
}>()

const isDragging = ref(false)
const activeTooltipIndex = ref(-1)
const userStore = useUserStore()
const connections = reactive(new Map<string, Transport>())
const getConnectionKey = (startId: number, endId: number) => `${startId}-${endId}`
const emit = defineEmits(['update:spots', 'transportClick', 'delete', 'transport-update', 'mapRef', 'show-analysis', 'add-marker','clear-markers'])
const importedPlanId = ref(null)
const isWheelProcessing = ref(false)

const DEFAULT_TIPS = {
  visiting_tips: '请先点击获取AI建议',
  detailed_analysis: '暂无详细分析',
  budget_estimation: '暂无预算信息',
  recommended_duration: '暂无推荐时长'
}

const spotsList = computed({
  get: () => props.spots,
  set: (value) => emit('update:spots', value)
})

// 初始化交通连接
const initConnection = async (startId: number, endId: number) => {
  const key = getConnectionKey(startId, endId)
  if (!connections.has(key)) {
    connections.set(key, {
      startId,
      endId,
      mode: '步行',
      visible: false
    })
    await updateTransportation(key)
  }
}

// 添加计算属性获取分析结果
const getSpotAnalysis = (spot: Spot) => {
  // console.log('Current spot:', spot)
  // console.log('Analysis results:', props.spotAnalysisResults)
  const analysis = props.spotAnalysisResults.find(
    result => result.spotId === spot.attractionId
  )?.analysis
  console.log('Found analysis:', analysis)

  if (!analysis) {
    // console.warn(`未找到匹配结果: 景点ID=${spot.attractionId}, 名称=${spot.name}`)

    return DEFAULT_TIPS

  }
  return analysis
}

// 获取交通连接信息
const getConnectionInfo = (index: number) => {
  const start = spotsList.value[index]
  const end = spotsList.value[index + 1]
  if (!start || !end) return null

  const key = getConnectionKey(start.attractionId, end.attractionId)
  return connections.get(key)
}

// 删除景点，提交给父组件处理
const handleDelete = (index: number) => {
  // 获取要删除的景点
  const spotToDelete = spotsList.value[index]

  // 先发出删除事件，让父组件处理地图标记的移除
  emit('delete', spotToDelete.attractionId)

  // 然后从列表中移除该景点
  spotsList.value.splice(index, 1)
}

// 添加点击icon传递信息处理方法
const handleRobotClick = (element: Spot) => {
  const analysis = props.spotAnalysisResults.find(
    result => result.spotId === element.attractionId
  )
  if (analysis) {
    emit('show-analysis', analysis)
    console.log('点击icon传递信息:', analysis)
  }
}

// 拖拽开始和结束时的处理
const dragStart = () => {
  isDragging.value = true
}

const dragEnd = () => {
  isDragging.value = false
}

const showTooltip = (index: number) => {
  activeTooltipIndex.value = index
}

const hideTooltip = () => {
  activeTooltipIndex.value = -1
}

const clearConnections = () => {
  connections.clear()
}


// 处理滚轮事件,通过滚轮切换交通方式
const handleWheel = async (event: WheelEvent, index: number) => {
  // 如果正在处理中，直接返回
  if (isWheelProcessing.value) {
    return
  }

  event.preventDefault()
  const start = spotsList.value[index]
  const end = spotsList.value[index + 1]
  const key = getConnectionKey(start.attractionId, end.attractionId)
  const connection = connections.get(key)
  if (!connection) return

  // 设置处理状态为true
  isWheelProcessing.value = true

  try {
    // 切换路线显示
    await props.mapRef.toggleRoute(connection.startId, connection.endId, connection.mode, true, false)

    const modes = ['步行', '骑行', '驾车'] as const
    const currentIndex = modes.indexOf(connection.mode)
    const direction = event.deltaY > 0 ? 1 : -1
    const nextIndex = (currentIndex + direction + modes.length) % modes.length

    connections.set(key, {
      ...connection,
      mode: modes[nextIndex]
    })

    await updateTransportation(key)
  } finally {
    // 添加短暂延迟后重置状态
    setTimeout(() => {
      isWheelProcessing.value = false
    }, 500) // 500ms 的冷却时间
  }
}

// 更新交通信息,实时计算路线并处理地图显示
const updateTransportation = async (connectionKey: string) => {
  const connection = connections.get(connectionKey)
  if (!connection) return

  const start = spotsList.value.find(spot => spot.attractionId === connection.startId)
  const end = spotsList.value.find(spot => spot.attractionId === connection.endId)
  if (!start || !end) return

  try {
    let result
    switch (connection.mode) {
      case '步行':
        result = await props.mapRef.calculateWalkingRoute(start, end)
        break
      case '骑行':
        result = await props.mapRef.calculateRidingRoute(start, end)
        break
      case '驾车':
        result = await props.mapRef.calculateDrivingRoute(start, end)
        break
    }

    connections.set(connectionKey, {
      ...connection,
      duration: result.duration,
      distance: result.distance
    })

    // 同步到地图
    props.mapRef.toggleRoute(connection.startId, connection.endId, connection.mode, false, connection.visible)
  } catch (error) {
    console.error('路线计算失败:', error)
  }
}


// 获取交通信息文本
const getTransportText = (index: number) => {
  const connection = getConnectionInfo(index)
  if (!connection) return '计算中...'

  const { mode, duration, distance } = connection
  if (!duration || !distance) return '计算中...'

  // 格式化距离
  const formattedDistance = distance < 1000
    ? `${Math.round(distance)}米`
    : `${(distance / 1000).toFixed(1)}公里`

  return `${mode} ${formattedDistance} ${duration}分钟`
}


// 切换路线显示,与地图相对应
const toggleRoute = (index: number) => {
  const start = spotsList.value[index]
  const end = spotsList.value[index + 1]
  const key = getConnectionKey(start.attractionId, end.attractionId)
  const connection = connections.get(key)
  if (!connection) return

  const newVisible = !connection.visible
  connections.set(key, {
    ...connection,
    visible: newVisible
  })

  props.mapRef.toggleRoute(connection.startId, connection.endId, connection.mode, false, newVisible)
}

// 序列化分析数据
const serializeAnalysis = (analysis: SpotAnalysisDetail['analysis']) => {
  return JSON.stringify({
    visiting_tips: analysis.visiting_tips,
    budget_estimation: analysis.budget_estimation,
    recommended_duration: analysis.recommended_duration,
    detailed_analysis: analysis.detailed_analysis
  })
}

//保存用户规划，同步到数据库
const handleSavePlan = async (formData) => {
  try {
    if (importedPlanId.value) {
      await deleteTravelPlan(importedPlanId.value)
    }
    // 1. 创建旅游计划
    const planResponse = await createTravelPlan({
      userId: userStore.userInfo?.userId, // 从用户store获取
      planName: formData.planName,
      startDate: new Date().toISOString(),
      endDate: new Date().toISOString(),
      status: formData.status,
      travelersInfo: formData.travelersInfo,
      budget: formData.budget,
      gptAnalysis: ''
    })

    if (!planResponse?.data?.planId) {
      const errorMsg = `创建计划失败: 服务器响应异常 - ${JSON.stringify(planResponse)}`
      console.error(errorMsg)
      return
    }

    const planId = planResponse.data.planId

    // 2. 添加计划景点
    for (let i = 0; i < spotsList.value.length; i++) {
      const spot = spotsList.value[i]
      const analysis = props.spotAnalysisResults.find(
        result => result.spotId === spot.attractionId
      )?.analysis

      await createPlanAttraction({
        planId,
        attractionId: spot.attractionId,
        visitDay: 1,
        visitOrder: i + 1,
        estimatedDuration: '2小时',
        gptAnalysis: analysis ? serializeAnalysis(analysis) : '',
        visitNotes: ''
      })
    }

    // 3. 添加交通计划
    for (const [key, connection] of connections.entries()) {
      await createTransportationPlan({
        planId,
        fromAttractionId: connection.startId,
        toAttractionId: connection.endId,
        transportOrder: 1,
        transportType: connection.mode,
        distance: 0,
        cost: 0,
        routeDetails: '默认路线'
      })
    }

    importedPlanId.value = null

    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 解析分析数据
const parseAnalysis = (analysisJson: string): SpotAnalysisDetail['analysis'] | null => {
  try {
    if (!analysisJson) return null
    const parsed = JSON.parse(analysisJson)
    return {
      visiting_tips: parsed.visiting_tips,
      budget_estimation: parsed.budget_estimation,
      recommended_duration: parsed.recommended_duration,
      detailed_analysis: parsed.detailed_analysis
    }
  } catch (e) {
    console.error('解析分析数据失败:', e)
    return null
  }
}

// 导入计划，清空当前计划并导入新计划
const importPlan = async (planId) => {
  try {
    isWheelProcessing.value = false

    importedPlanId.value = planId

    const currentSpotIds = spotsList.value.map(spot => spot.attractionId)

    emit('clear-markers', currentSpotIds)

    spotsList.value = []
    connections.clear()

    await props.mapRef.clearAllRoutes()

    const planAttractionsRes = await getPlanAttractionListByPlanId(planId, 1, 100)
    if (!planAttractionsRes?.data) {
      throw new Error('获取计划景点失败')
    }

    // 按visitOrder排序
    const orderedAttractions = planAttractionsRes.data
      .sort((a, b) => a.visitOrder - b.visitOrder)

    const analysisResults: SpotAnalysisDetail[] = []

    // 合并后的单个循环，同时处理景点数据和分析数据
    for (const planAttraction of orderedAttractions) {
      const attractionRes = await getAttractionInfo(planAttraction.attractionId)
      if (!attractionRes?.data) continue

      // 解析分析数据
      const analysis = parseAnalysis(planAttraction.gptAnalysis)
      if (analysis) {
        analysisResults.push({
          spotId: planAttraction.attractionId,
          name: attractionRes.data.name,
          analysis: analysis
        })
      }

      // 添加景点数据
      const spotData = {
        ...attractionRes.data,
        duration: planAttraction.estimatedDuration ?
          parseInt(planAttraction.estimatedDuration) : 120,
        aiSuggestion: analysis ? '已恢复AI建议' : '暂无建议'
      }

      spotsList.value.push(spotData)
      emit('add-marker', spotData)
    }

    // 更新分析结果
    props.spotAnalysisResults.splice(0, props.spotAnalysisResults.length, ...analysisResults)

    // 5. 获取并设置交通信息
    const transportRes = await getTransportationPlansByPlanId(planId, 1, 100)
    if (transportRes?.data) {
      for (const transport of transportRes.data) {
        const key = getConnectionKey(transport.fromAttractionId, transport.toAttractionId)
        connections.set(key, {
          startId: transport.fromAttractionId,
          endId: transport.toAttractionId,
          mode: transport.transportType as '步行' | '骑行' | '驾车',
          visible: false,
          distance: transport.distance,
          duration: transport.duration
        })

        // 更新地图路线
        await updateTransportation(key)
      }
    }

    ElMessage.success('导入成功')
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error('导入失败，请重试')
  }
}

watch(() => spotsList.value, async (newList, oldList) => {
  if (!oldList) return

  // 获取所有当前应该存在的连接
  const currentConnections = new Set<string>()
  for (let i = 0; i < newList.length - 1; i++) {
    const key = getConnectionKey(newList[i].attractionId, newList[i + 1].attractionId)
    currentConnections.add(key)
  }

  // 删除不再需要的连接
  for (const [key, connection] of connections.entries()) {
    if (!currentConnections.has(key)) {
      // 通知地图删除路线
      props.mapRef.toggleRoute(connection.startId, connection.endId, connection.mode, true, false)
      connections.delete(key)
    }
  }

  // 添加新的连接
  for (const key of currentConnections) {
    if (!connections.has(key)) {
      const [startId, endId] = key.split('-').map(Number)
      await initConnection(startId, endId)
    }
  }
}, { deep: true })

defineExpose({
  handleSavePlan,
  importPlan,
  clearConnections,  // 暴露新方法
  spotsList: computed(() => spotsList.value),
})
</script>

<style scoped>
.spot-container {
  margin-bottom: 0 px;
  position: relative;
  color: black;
  isolation: isolate;
  /* 创建新的堆叠上下文 */
}

.spot-card {
  position: relative;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 1;
}

.truncated-text {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  /* 限制为2行 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  margin: 0;
  line-height: 1.5;
  color: #fff;
  font-size: 12px;
}

.tooltip-hint {
  position: absolute;
  bottom: 8px;
  right: 8px;
  font-size: 11px;
  color: rgba(255, 255, 255, 0.7);
  font-style: italic;
}

.robot-tooltip {
  position: relative;
  padding-bottom: 24px;
  /* 为提示文字留出空间 */
}

.robot-icon {
  position: absolute;
  right: 12px;
  bottom: -8px;
  width: 24px;
  height: 24px;
  background: #fff;
  border-radius: 50%;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 3;
}

.robot-icon:hover {
  transform: scale(1.1);
}

.robot-tooltip {
  position: absolute;
  bottom: 100%;
  right: -10px;
  /* 调整这个值以确保 tooltip 不被遮挡 */
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
  white-space: normal;
  margin-bottom: 8px;
  z-index: 1000;
  width: 240px;
  /* 可以调宽一点 */
  max-width: 300px;
  /* 设置最大宽度 */
  word-wrap: break-word;
  transition: opacity 0.2s ease-in-out;
}

.robot-tooltip::after {
  content: '';
  position: absolute;
  bottom: -5px;
  right: 20px;
  /* 调整以匹配 tooltip 的位置 */
  border-width: 5px;
  border-style: solid;
  border-color: rgba(0, 0, 0, 0.8) transparent transparent transparent;
}

.transport-button {
  width: 100%;
  height: 32px;
  background: #f5f5f5;
  border-radius: 16px;
  overflow: hidden;
  position: relative;
  cursor: pointer;
  user-select: none;
  margin: 12px 0;
  z-index: 1;
}

.transport-text-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.transport-text {
  position: absolute;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.transport-text.active {
  background-color: #e6f1ff;
  color: #409EFF;
}

.slide-enter-active,
.slide-leave-active {
  transition: transform 0.3s ease;
}

.slide-enter-from {
  transform: translateX(100%);
}

.slide-leave-to {
  transform: translateX(-100%);
}

.slide-enter-to,
.slide-leave-from {
  transform: translateX(0);
}

.spot-name {
  font-weight: bold;
  margin-bottom: 8px;
}

.spot-desc {
  color: #666;
  font-size: 14px;
}

.spot-time {
  color: #999;
  font-size: 12px;
}

.delete-button {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 2;
  transform: scale(0.8);
  background-color: rgb(247, 116, 116);
  border: 0cm;
}

.delete-button :deep(.el-icon) {
  font-size: 12px;
}



.tooltip-section {
  margin-bottom: 12px;
}

.tooltip-section h4 {
  color: #409EFF;
  margin: 0 0 4px;
  font-size: 14px;
}

.tooltip-section p {
  margin: 0;
  font-size: 12px;
  line-height: 1.5;
  color: #fff;
}
</style>